/*
 * common.c
 *
 *  Created on: Dec 2, 2013
 *      Author: SAGUET Julien et POCREAU Aymeric
 */

#include "../includes/common.h"

// Creation de la socket d'ecoute
int create_socket(char *ip, int port) {
	int socketEcoute;
	struct sockaddr_in dest;

	/*---Create the socket---*/

	if ((socketEcoute = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("Socket");
		exit(EXIT_FAILURE);
	}
	int optval = 1;
	setsockopt(socketEcoute, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
	/*---Initialize server address/port struct---*/

	memset(&dest, '\0', sizeof(dest));
	dest.sin_family = AF_INET;
	dest.sin_port = htons(port);
	inet_aton(ip, &dest.sin_addr);

	/*---Connect to server---*/
	if (connect(socketEcoute, (struct sockaddr *) &dest,
			sizeof(struct sockaddr)) < 0) {
		perror("Connect");
		exit(EXIT_FAILURE);
	}
	return socketEcoute;
}

// Creation de la socket utilisée pour l'envoie de fichier
int create_socket_file(int* port_file) {
	int socketEcoute;
	struct sockaddr_in dest;

	/*---Create the socket---*/

	if ((socketEcoute = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("Socket");
		exit(EXIT_FAILURE);
	}
	int optval = 1;
	setsockopt(socketEcoute, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
	/*---Initialize server address/port struct---*/

	memset(&dest, 0, sizeof(dest));
	dest.sin_addr.s_addr = htonl(INADDR_ANY);
	dest.sin_family = AF_INET;
	dest.sin_port = *port_file;

	bind(socketEcoute, (struct sockaddr *) &dest, sizeof(dest));

	/* get assigned port */
	struct sockaddr_in sock_info;
	socklen_t size = sizeof(sock_info);
	getsockname(socketEcoute, (struct sockaddr *) &sock_info, &size);
	*port_file = sock_info.sin_port;
	printf("port : %d\n", *port_file);

	if (listen(socketEcoute, BACKLOG) < 0) {
		perror("listen");
		exit(EXIT_FAILURE);
	}

	return socketEcoute;
}

// Fonction permettant la reception de caractères
int readline(int fd, void *str, int max_len) {
	int n, rc;
	char c;
	char* buffer;

	buffer = str;
	for (n = 1; n < max_len; n++) {
		if ((rc = read(fd, &c, 1)) == 1) {
			*buffer++ = c;
			if (c == '\n') {
				*(buffer - 1) = '\0';
				break;
			}
		} else {
			if (rc == 0) {
				if (n == 1)
					return 0;
				else
					break;
			}
			if (rc == -1) {
				if (errno == EINTR)
					continue;
				else
					return -1;
			}
		}
	}
	*buffer-- = '\0';
	return n;
}

// Fonction permettant l envoie de caractères
int sendline(int fd, const void *str, size_t maxlen) {
	int nleft; //caractères restant à écrire
	int nwritten; // caractères déjà écrits

	const char* buffer;

	buffer = str;
	nleft = maxlen;
	while (nleft > 0) {
		if ((nwritten = write(fd, buffer, nleft)) < 0) {
			if (errno == EINTR)
				nwritten = 0;
			else
				return -1;
		}
		nleft -= nwritten;
		buffer += nwritten;
	}
	return maxlen;
}

void clean(char *buffer) {
	char* p = NULL;
	p = strchr(buffer, '\n');
	if (p == NULL) {
		int c;
		while ((c = getchar()) != '\n' && c != EOF) {
		}
	}
}
